package com.zone.mybatis.datasource.unpooled;

import cn.hutool.core.convert.Convert;
import com.zone.mybatis.datasource.DataSourceFactory;
import com.zone.mybatis.reflection.MetaObject;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author: zongzi
 * @description: TODO
 * @date: 2023/12/24
 */
public class UnpooledDataSourceFactory implements DataSourceFactory {
    protected DataSource dataSource;

    public UnpooledDataSourceFactory() {
        this.dataSource = new UnpooledDataSource();
    }

    @Override
    public void setProperties(Properties properties) {
        MetaObject metaObject = MetaObject.forObject(dataSource);
        for (Object key : properties.keySet()) {
            String propertyName = (String) key;
            if (metaObject.hasSetter(propertyName)) {
                Object propertyValue = properties.get(propertyName);
                Class<?> setType = metaObject.getSetType(propertyName);
                Object convertValue = Convert.convert(setType, propertyValue);
                metaObject.set(propertyName, convertValue);
            }
        }
    }

    @Override
    public DataSource getDataSource() {
        return dataSource;
    }
}
